import 'package:get/get.dart';
import '../models/todo.dart';
import '../services/todo_service.dart';
import '../../../core/state/page_state.dart';
import '../../../core/network/api_client.dart';

class HomeController extends GetxController {
  final TodoService _todoService;

  HomeController(this._todoService);

  // 响应式状态
  final Rx<PageState> _pageState = PageState.loading.obs;
  final RxList<Todo> _todos = <Todo>[].obs;
  final RxString _errorMessage = ''.obs;
  final RxBool _isRefreshing = false.obs;

  // Getters
  PageState get pageState => _pageState.value;
  List<Todo> get todos => _todos;
  String get errorMessage => _errorMessage.value;
  bool get isRefreshing => _isRefreshing.value;

  @override
  void onInit() {
    super.onInit();
    loadTodos();
  }

  Future<void> loadTodos() async {
    try {
      _pageState.value = PageState.loading;
      _errorMessage.value = '';
      
      final todos = await _todoService.getTodos();
      
      if (todos.isEmpty) {
        _pageState.value = PageState.empty;
      } else {
        _todos.assignAll(todos);
        _pageState.value = PageState.success;
      }
    } catch (error) {
      _pageState.value = ApiClient.handleError(error);
      _errorMessage.value = ApiClient.getErrorMessage(error);
    }
  }

  Future<void> refreshTodos() async {
    try {
      _isRefreshing.value = true;
      
      final todos = await _todoService.getTodos();
      
      if (todos.isEmpty) {
        _pageState.value = PageState.empty;
      } else {
        _todos.assignAll(todos);
        _pageState.value = PageState.success;
      }
      
      // 显示成功提示
      Get.snackbar(
        '刷新成功',
        '数据已更新',
        snackPosition: SnackPosition.BOTTOM,
        duration: const Duration(seconds: 2),
      );
    } catch (error) {
      _pageState.value = ApiClient.handleError(error);
      _errorMessage.value = ApiClient.getErrorMessage(error);
      
      // 显示错误提示
      Get.snackbar(
        '刷新失败',
        ApiClient.getErrorMessage(error),
        snackPosition: SnackPosition.BOTTOM,
        duration: const Duration(seconds: 3),
      );
    } finally {
      _isRefreshing.value = false;
    }
  }

  void retryLoad() {
    loadTodos();
  }

  void toggleTodoStatus(int index) {
    if (index >= 0 && index < _todos.length) {
      final todo = _todos[index];
      final updatedTodo = Todo(
        id: todo.id,
        title: todo.title,
        completed: !todo.completed,
      );
      _todos[index] = updatedTodo;
    }
  }
}